<?php

namespace app\api\logic;

use app\common\exception\BusinessException;
use app\common\model\AgentRelation;
use app\common\model\OrderBonusItem;
use app\common\model\OrderBonusSettlement;
use app\common\model\UserShareImage;
use app\common\service\GlobalsVariableService;
use app\common\service\UserService;

class Promote
{

    /**
     * getInfo
     * @param $param
     * @return array[]
     */
    public function getInfo($param): array
    {
        // 查询用户信息
        $userId = $param['userId'];
        $userInfo = app(UserService::class)->getUserById($userId);
        if ($userInfo['is_agent'] != 1) {
            throw new BusinessException('非法请求');
        }
        return [
            'user' => [
                'today_income' => $this->getTodayIncome($userId),
                'bonus_rate_one' => $userInfo['bonus_rate_one'] . '%',
                'bonus_rate_two' => $userInfo['bonus_rate_two'] . '%',
            ],
            'rule' => [
                '1、每结算一笔订单，分红比例增加1%',
                '2、您的客户购买(会员|题库|视频|论文|报名|源码|数据)您均可获得分红',
                '3、第三方支付接口费率试运营期间由平台承担',
                '4、订单7天内无退款进入结算期，满10元自动结算，结算失败请检查您的收款账户是否正确',
                '5、通过宣传素材、转发小程序均可正常推广订单',
            ],
        ];
    }

    /**
     * 获取今日收入
     * @param $userId
     * @return float
     */
    private function getTodayIncome($userId): float
    {
        // 查询条件
        $s_time = strtotime(date('Y-m-d 00:00:00'));
        $e_time = time();
        $where = [
            ['agent_id', '=', $userId],
            //['create_time', 'between', [$s_time, $e_time]],
        ];

        // 查询数据
        $orderBonusItemModel = new OrderBonusItem();
        return $orderBonusItemModel->where($where)->sum('bonus_amount');
    }

    /**
     * 我的下级
     * @param array $data
     * @return mixed
     */
    public function mySubordinate(array $data)
    {
        // 提取参数
        $page = $data['page'];
        $limit = 15;
        $userId = $data['userId'];

        // 检查请求
        $userInfo = app(UserService::class)->getUserById($userId, 'is_agent');
        if ($userInfo['is_agent'] != 1) {
            throw new BusinessException('非法请求');
        }

        // 查询字段
        $field = ['a.parent_uid', 'a.create_time', 'a.relation_level', 'b.id', 'b.nickname', 'b.avatar'];

        // 查询条件
        $where = [['parent_uid', '=', $userId]];

        // 排序方式
        $orderBy = ['a.create_time' => 'desc'];

        // 查询数据
        $agentRelationModel = new AgentRelation();
        $list = $agentRelationModel
            ->alias('a')
            ->leftJoin('user b', 'a.child_uid = b.id')
            ->where($where)
            ->order($orderBy)
            ->field($field)
            ->page($page)
            ->limit($limit)
            ->select()
            ->toArray();

        // 填充数据
        foreach ($list as $key => $val) {
            $list[$key]['add_date'] = date('m-d', $val['create_time']);
            $list[$key]['add_time'] = date('H:i', $val['create_time']);
            $list[$key]['relation_level_name'] = $agentRelationModel->relation_level_map[$val['relation_level']] ?? '-';
        }

        // 返回
        return $list;
    }

    /**
     * 成交订单
     * @param array $param
     * @return mixed
     */
    public function completedOrder(array $param)
    {
        // 提取参数
        $page = $param['page'];
        $limit = 15;
        $userId = $param['userId'];

        // 检查请求
        $userInfo = app(UserService::class)->getUserById($userId, 'is_agent');
        if ($userInfo['is_agent'] != 1) {
            throw new BusinessException('非法请求');
        }

        // 查询字段
        $field = ['a.order_amount', 'a.bonus_rate', 'a.bonus_amount', 'a.create_time', 'a.relation_level', 'a.is_settlement', 'a.is_build_settlement_order', 'b.id', 'b.order_sn'];

        // 查询条件
        $where = [['a.agent_id', '=', $userId]];

        // 排序方式
        $orderBy = ['a.create_time' => 'desc'];

        // 查询数据
        $agentRelationModel = new AgentRelation();
        $orderBonusItemModel = new OrderBonusItem();
        $list = $orderBonusItemModel
            ->alias('a')
            ->leftJoin('order b', 'a.order_id = b.id')
            ->where($where)
            ->order($orderBy)
            ->field($field)
            ->page($page)
            ->limit($limit)
            ->select()
            ->toArray();

        // 填充数据
        foreach ($list as $key => $val) {
            $list[$key]['add_date'] = date('Y-m-d', $val['create_time']);
            $list[$key]['bonus_rate_name'] = $val['bonus_rate'] ? $val['bonus_rate'] . '%' : '-';
            $list[$key]['relation_level_name'] = $agentRelationModel->relation_level_map[$val['relation_level']] ?? '-';
        }

        // 返回
        return $list;
    }

    /**
     * 结算记录
     * @param array $param
     * @return mixed
     */
    public function settlementOrder(array $param)
    {
        // 提取参数
        $page = $param['page'];
        $limit = 15;
        $userId = $param['userId'];

        // 检查请求
        $userInfo = app(UserService::class)->getUserById($userId, 'is_agent');
        if ($userInfo['is_agent'] != 1) {
            throw new BusinessException('非法请求');
        }

        // 查询条件
        $where = [['agent_id', '=', $userId]];

        // 排序方式
        $orderBy = ['create_time' => 'desc'];

        // 查询数据
        $orderBonusSettlementModel = new OrderBonusSettlement();
        $list = $orderBonusSettlementModel
            ->where($where)
            ->order($orderBy)
            ->page($page)
            ->limit($limit)
            ->select()
            ->toArray();

        // 填充数据
        foreach ($list as $key => $val) {
            $list[$key]['status_name'] = $orderBonusSettlementModel->status_map[$val['status']] ?? '-';
            $list[$key]['settlement_time_name'] = formatTime($val['settlement_time'], 'Y-m-d H:i:s', '暂未结算');
        }

        // 返回
        return $list;
    }

    /**
     * getShareImage
     * @param $param
     * @return array
     * @throws
     */
    public function shareImage($param): array
    {
        // 提取参数
        $userId = $param['userId'];
        $appId = GlobalsVariableService::get('appId');

        // 预生成
        app(UserShareImage::class)->build($appId, $userId);

        // 查询数据
        $where = [['uid', '=', $userId]];
        $list = app(UserShareImage::class)->where($where)->select()->toArray();
        if (!$list) {
            throw new BusinessException('账号未生成宣传素材，请联系管理员');
        }

        // 返回
        return array_column($list, 'url');
    }
}